// pages/bindWechat/bindWechat.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Base64 from '../../utils/Base64.js';
const util = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //发送验证码按钮文字
    sendBtnMsg:'发送验证码',
    //发送验证码按钮是否禁用
    disabledMsg: false,
    //正确的验证码
    rightCode:'',
    //错误提示
    smsMessage:'',
    //当前用户
    user:{},
    //是否显示表单
    showForm:true,
    //已经绑定的提示
    showBind:false,
    //验证码
    checkCode:null,
    //关注公众号对话框
    showWeChatDia:false,
    //公众号名称
    officialName:'',
    //绑定的id
    bindId:null,
    //勾选协议
    checked: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      //登录用户
      user: app.globalData.userInfo,
      //公众号名称
      officialName: app.globalData.officialName,
    })

    //检测登录用户是否已绑定微信
    this.checkBindWechat();
  },

  //检测登录用户是否已绑定微信
  checkBindWechat(){
    let param = {
      isAuth: false,
      className: 'wechatLogin',
      data: {
        userId: app.globalData.userInfo.id,
        selectFields: ['id'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param).then(res=>{  
      if(res.data.data && res.data.data.result && res.data.data.result.length){       
        //已经绑定过了
        this.setData({
          showForm: false,
          showBind:true,
          bindId:res.data.data.result[0].id
        })  
      }else{
        this.setData({
          showWeChatDia: true
        })
      }
    }).catch((error) => {
    })
  },  

  //点击发送验证码
  sendCode(){
    let _this=this;
    wx.getSetting({
      success (res){
        if (res.authSetting['scope.userInfo']) {
          //已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {
              Toast.loading({
                duration: 0,
                forbidClick: true
              });

              let phone = _this.data.user.personalPhone;
              if(phone){
                let parameter={
                  personalPhone: phone,
                  appId:[app.globalData.myAppId]
                }

                CommonService.sendSms(parameter).then(res=>{
                  if(res.data.data){
                    //查询验证码
                    _this.querySms(phone,res.data.data.bizId);
                  }else{
                    Toast.fail('抱歉出错了');
                  }
                }).catch((error) => {
                  Toast.fail('抱歉出错了');
                })
              }else{
                Toast('请到管理后台设置您的手机号码');
              }
            }
          })
        }
      }
    })  
  },

  //查询验证码
  querySms(phone,bizId){
    let parameter={
      personalPhone: phone,
      bizId:bizId
    }

    CommonService.querySms(parameter).then(res=>{
      Toast.clear();
      if(res.data.data){
        Toast.success('验证码已发送');

        console.log('验证码');
        console.log(res.data.data.code);

        this.setData({
          checkCode: res.data.data.code
        })

        //重新发送倒计时
        let time = null;
        let num = 60;

        time = setInterval(() => {
          num--;
          this.setData({
            disabledMsg:true,
            sendBtnMsg: num + '秒后重新发送'
          });
          if (num == 0) {
            clearInterval(time);
            this.setData({
              disabledMsg: false,
              sendBtnMsg: '发送验证码'
            });
          }
        }, 1000);
      }else{
        Toast.fail('抱歉出错了');
      }

    }).catch((error) => {
      Toast.fail('抱歉出错了');
    })
  },

  //获取输入的验证码
  getCode(e) {
    this.setData({
      sms: e.detail,
      smsMessage:'',
      disabled: false
    });
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //提交表单-验证短信验证码
  submitForm(e){
    if(this.data.checked){
      let sms = e.detail.value.sms;
      if (sms) {
        if (sms == this.data.checkCode){
          wx.redirectTo({
            url: '/pages/authorize/authorize'
          })
        }else{
          this.setData({
            smsMessage: '请输入正确的验证码',
            disabled: true
          });
        }
      }else{
        this.setData({
          smsMessage: '请输入验证码',
          disabled: true
        });
      }
    }else{
      Toast.fail('请同意《客户服务协议》和《用户隐私政策》');
    }
  },

  //跳转解绑
  goToDeleteBind(){
    let bindId=this.data.bindId;
    wx.redirectTo({
		  url: '/pages/bindWechatDelete/bindWechatDelete?id='+bindId
		})
  },

  //确认-跳转关注公众号
  confirmWeChat(){
    wx.navigateTo({
      url: "/pages/weChatOfficial/weChatOfficial"
    })
  },

  //返回首页
  goToHome(){
    wx.reLaunch({
      url: "/pages/personalCenter/personalCenter"
    })
  },

  //无验证码这一步骤的跳转绑定
  goToBind(){
    wx.redirectTo({
      url: '/pages/authorize/authorize'
    })
  },

  //勾选协议
  onChange(event) {
    this.setData({
      checked: event.detail,
      disabled: false
    })
  },

  //客户服务协议
  goToAgree(){
    wx.navigateTo({
      url: "/packageA/pages/serviceAgreement/serviceAgreement"
    })
  },

  //用户隐私政策
  goToPrivacy(){
    wx.navigateTo({
      url: "/packageA/pages/servicePrivacy/servicePrivacy"
    })
  },  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
